package com.apes.fn.scm.retailOrder.service.account.retailReturn;

import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.model.RetailOrderItem;
import com.apes.fn.scm.retailOrder.service.account.RetailReturnVoucher;
import com.apes.fn.scm.retailReturn.RetailReturn;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.scm.account.account.model.AccountingMethod;
import com.apes.scm.account.account.model.InventoryMode;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherItem;
import com.apes.scm.voucher.repository.VoucherRepository;
import com.apes.scm.voucher.service.BusinessType;
import com.apes.scm.voucher.service.VoucherType;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author wuq
 * @Date 2021-11-22
 */
@RetailReturnAccount(value = "returnCrossIC", name = "零售有单异业退货生成销售退回凭证")
@Service
public class RetailReturnCrossICVoucherService implements RetailReturnVoucher {

    @Override
    public Voucher process(RetailReturn retailReturn) {
        Voucher voucher = new Voucher();
        voucher.setReturned(true);
        voucher.setBusinessType(BusinessType.SALE_RETURN);
        voucher.setInventoryMode(InventoryMode.IM_OWN);     //设置库存模式：自有经销
        voucher.setAccountingMethod(AccountingMethod.AM_PURCHASE);  // 核算方式：采购

        // 主表信息
        voucher.setCompany(retailReturn.getCompany());
        voucher.setDept(retailReturn.getDept());
        voucher.setClerk(retailReturn.getClerk()); //业务员
        voucher.setPartner(retailReturn.getCustomer());

        voucher.setScene(retailReturn.getScene());
        voucher.setOrigin(retailReturn.getId());
        voucher.setOriginBusinessType(retailReturn.getInnerBusinessType());
        voucher.setSource(retailReturn.getId());
        voucher.setSourceBusinessType(retailReturn.getInnerBusinessType());

        // 找原销售凭证
        Voucher source = findVoucher(retailReturn.getSaleOrder().getId());
        voucher.setVoucher(source);

        // 异业合作明细单独处理
        voucher.setVoucherItems(getItems(retailReturn, voucher));
        return voucher;
    }

    private Voucher findVoucher(String businessId) {
        String businessType = RetailOrder.class.getSimpleName();
        List<Voucher> vouchers = SpringManager.getBean(VoucherRepository.class).findAll(
                        JpaDsl.toCriteriaByEq("originBusinessType", businessType, "origin", businessId, "source", businessId, "voucherType", "CUSTOMER_SALE"))
                .stream().filter(v -> !Objects.equals(VoucherType.E_MAINTAIN, v.getClassification())).collect(Collectors.toList());
        if (vouchers.size() > 1) throw new RuntimeException("根据源单据查询到多个分销凭证！请检查业务凭证！");

        Voucher voucher = vouchers.stream().findFirst().orElse(null);
        if (voucher == null) {
            voucher = SpringManager.getBean(VoucherRepository.class).findOne(
                    JpaDsl.toCriteriaByEq("sourceBusinessType", businessType, "source", businessId, "voucherType", "CUSTOMER_SALE")).orElse(null);
        }
        return voucher;
    }

    /**
     * 获取异业合作明细
     *
     * @param saleReturn RetailReturn
     * @param voucher    Voucher
     * @return Set<VoucherItem>
     */
    private Set<VoucherItem> getItems(RetailReturn saleReturn, Voucher voucher) {
        Set<VoucherItem> voucherItems = new HashSet();
        saleReturn.getSaleItems().forEach(
                saleReturnItem -> {
                    VoucherItem voucherItem = new VoucherItem();
                    voucherItem.setVoucher(voucher);    // 凭证主表
                    voucherItem.setOwner(saleReturnItem.getOwner());

                    voucherItem.setProduct(saleReturnItem.getProduct());
                    voucherItem.setUom(saleReturnItem.getUom());
                    voucherItem.setProductQty(-1.00 * saleReturnItem.getProductUomQty());

                    voucherItem.setOriginItemId(saleReturnItem.getId());
                    voucherItem.setSourceItemId(String.valueOf(saleReturnItem.getId()));
                    voucherItem.setSupplier(saleReturnItem.getSupplier());

                    VoucherItem source = voucherItem.findVoucherItem(saleReturnItem.getRetailOrderItem().getId());
                    if (source == null)
                        throw new RuntimeException("没有找到原单明细：" + saleReturnItem.getRetailOrderItem().getId() + " 的业务凭证！");
                    voucherItem.setVoucherItem(source);

                    // 重新赋值税率、商品价格、折扣
                    voucherItem.setTax(source.getTax());
                    voucherItem.setPriceUnit(source.getPriceUnit());
                    voucherItem.setDiscount(-1.00 * Math.abs(source.getDiscount()));
                    voucherItems.add(voucherItem);
                });
        return voucherItems;
    }

}
